package net.yunzhanyi.client.advice;

import com.alibaba.fastjson.JSON;
import net.yunzhanyi.client.utils.AjaxUtils;
import net.yunzhanyi.common.core.exception.NotLoginException;
import net.yunzhanyi.common.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author TingChang
 * @code AjaxExceptionAdivce
 * @date 2021/9/23
 * description:
 */

@RestControllerAdvice
public class AjaxExceptionAdvice {

    Logger logger = LoggerFactory.getLogger(AjaxExceptionAdvice.class);

    @ExceptionHandler(Exception.class)
    public Object exception(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException {

        exception.printStackTrace();
        boolean isAjax = AjaxUtils.isAjax(request);
        if (isAjax) {
            logger.error("接口请求异常", exception);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            AjaxResult error = AjaxResult.error(500, exception.getMessage());
            String string = JSON.toJSONString(error);
            response.getWriter().print(string);
            return null;
        } else {
            if (exception instanceof NotLoginException) {
                try {
                    response.sendRedirect("/login");
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ModelAndView mv = new ModelAndView();
            mv.addObject("errorMessage", exception.getMessage());
            mv.setViewName("500");
            return mv;
        }
    }
}
